import { login, logout, getInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userId: '',
  username: '',
  nickname: '',
  email: '',
  phone: ''
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NICKNAME: (state, nickname) => {
    state.nickname = nickname
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password, captcha } = userInfo
    return new Promise((resolve, reject) => {
      login(username.trim(), password, captcha)
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_USER_ID', data.userId)
          commit('SET_USERNAME', data.username)
          setToken(data.token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          const { data } = response
          if (!data) {
            reject('获取用户信息失败，请重新登录')
          }
          
          const { userId, username, nickname, email, phone } = data
          
          commit('SET_USER_ID', userId)
          commit('SET_USERNAME', username)
          commit('SET_NICKNAME', nickname)
          commit('SET_EMAIL', email)
          commit('SET_PHONE', phone)
          
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 用户登出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout()
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_USER_ID', '')
          commit('SET_USERNAME', '')
          commit('SET_NICKNAME', '')
          commit('SET_EMAIL', '')
          commit('SET_PHONE', '')
          removeToken()
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 清除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_USER_ID', '')
      commit('SET_USERNAME', '')
      commit('SET_NICKNAME', '')
      commit('SET_EMAIL', '')
      commit('SET_PHONE', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 